package com.homegoods.area.ui.activity;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.util.Log;
import android.view.View;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.fastjson.JSON;
import com.homegoods.area.AreaEvent;
import com.homegoods.area.R;
import com.homegoods.area.databinding.AreaActivityAreaBinding;
import com.homegoods.area.item.AreaItem;
import com.homegoods.area.model.AreaModel;
import com.homegoods.area.presenter.AreaPresenter;
import com.homegoods.area.ui.view.IAreaView;
import com.homegoods.aroutercomment.ARouterPath;
import com.kedll.library.adapter.MultiSelectAdapter;
import com.kedll.library.adapter.MultiTypeAdapter;
import com.kedll.library.base.MyBaseFragmentActivity;
import com.kedll.library.util.RxBus;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.functions.Consumer;

/**
 * 选择地区
 *
 * @author QiQi
 */
@Route(path = ARouterPath.PATH_AREA)
public class AreaActivity extends MyBaseFragmentActivity<AreaActivityAreaBinding, AreaPresenter> implements IAreaView {

    private List<MultiSelectAdapter> adapters = new ArrayList<>();

    @Override
    public int getLayout() {
        return R.layout.area_activity_area;
    }

    @Override
    protected void initEvent() {
        mBinding.titleBar.setRightBtnClickListener(view -> finish());

        mBinding.tabArea.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                MultiSelectAdapter adapter = adapters.get(tab.getPosition());
                mBinding.list.setAdapter(adapter);

            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });

        mPresenter.getArea();
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);
        ARouter.getInstance().inject(this);
    }

    @Override
    protected AreaPresenter getPresenter() {
        return new AreaPresenter(this);
    }

    @SuppressLint("CheckResult")
    @Override
    public void setArea(int index, List<AreaModel> areaList) {
        MultiSelectAdapter<AreaModel> adapter = new MultiSelectAdapter<>(false);
        Observable.fromIterable(areaList)
                .compose(bindToLifecycle())
                .map(areaModel -> areaModel.createItem(adapter))
                .toList()
                .doOnSuccess(new Consumer<List<AreaItem>>() {
                    @Override
                    public void accept(List<AreaItem> areaItems) throws Exception {
                        Log.d(TAG, "accept: areaItems == " + JSON.toJSONString(areaItems));
                        adapter.setOnItemClickListener(new OnItemClickListener(index));
                        adapters.add(adapter);
                        mBinding.list.setAdapter(adapter);
                        TabLayout.Tab tab = mBinding.tabArea.newTab().setText("请选择");
                        mBinding.tabArea.addTab(tab, true);
                    }
                })
                .subscribe(data -> adapter.addAllWithClear(data));


    }

    private final class OnItemClickListener implements MultiTypeAdapter.OnItemClickListener<AreaModel> {

        private final int index;

        private OnItemClickListener(int index) {
            this.index = index;
        }


        @SuppressLint("CheckResult")
        @Override
        public void onItemClicked(View v, MultiTypeAdapter.IItem<AreaModel> iItem) {
            AreaModel area = iItem.getData();
            TabLayout.Tab tab = mBinding.tabArea.getTabAt(mBinding.tabArea.getTabCount() - 1);
            if (tab == null) {
                return;
            }

            tab.setText(area.getAreaName());
            tab.setTag(area);
            Log.d(TAG, "onItemClicked: isHaveChild == " + area.isHaveChild());
            if (area.isHaveChild()) {
                mPresenter.loadArea(index + 1, area.getItems());
            } else {
//                Observable.range(0, mBinding.tabArea.getTabCount())
//                        .map(integer -> (AreaModel) mBinding.tabArea.getTabAt(integer).getTag())
//                        .toList()
//                        .subscribe(areaModels -> {
//                            RxBus.getDefault().post(new AreaEvent(areaModels));
//                            finish();
//                        });
                String areaName = "";
                for (int i = 0; i < mBinding.tabArea.getTabCount(); i++) {
                    AreaModel model = (AreaModel) mBinding.tabArea.getTabAt(i).getTag();
                    areaName += model.getAreaName();
                    if (i == mBinding.tabArea.getTabCount() - 1) {
                        RxBus.getDefault().post(new AreaEvent(areaName, model.getId()));
                        finish();
                    }
                }
            }

//            Observable.range(index + 1, mBinding.tabArea.getTabCount() - 1)
//                    .compose(bindToLifecycle())
//                    .doOnComplete(() -> {
//                        if (!TextUtils.isEmpty(area.getItems())) {
//                            mPresenter.loadArea(index + 1, area.getItems());
//                        } else {
//                            Observable.range(0, mBinding.tabArea.getTabCount())
//                                    .map(integer -> (AreaModel) mBinding.tabArea.getTabAt(integer).getTag())
//                                    .toList()
//                                    .subscribe(areaModels -> RxBus.getDefault().post(new AreaEvent(areaModels)));
//                        }
//                    })
//                    .subscribe(i -> {
//                        adapters.remove(i);
//                        mBinding.tabArea.removeTabAt(i);
//                    });


        }
    }

}
